<?php
/**
 * Created by PhpStorm.
 * User: Merdan
 * Date: 2017/3/28
 * Time: 2:59
 */

namespace App\Services;
use App\Exceptions\AlreadyExistException;
use App\Exceptions\NotExistException;
use App\Models\Sku as SkuModel;

class Sku extends BaseService
{
    /**
     * 获取库存列表
     *
     * @param $limit
     * @param null $name
     * @param $category_id
     * @return mixed
     */
    public function getList($limit, $name = null, $category_id = null)
    {
        $canteen_id = auth()->user()->canteen->id;
        $sku = SkuModel::select()->where('canteen_id', $canteen_id)->with('product.category');
        if($name !== null){
            $sku->whereHas('product',function ($query) use ($name, $category_id){
                $query->where('name', 'like', "%{$name}%");
            });
        }
        if($category_id !== null){
            $sku->whereHas('product',function ($query) use ($category_id){
                if($category_id !== null){
                    $query->where('category_id', $category_id);
                }
            });
        }
        return $sku->paginate($limit);
    }

    /**
     * 获取单个库存信息
     *
     * @param $id
     * @return mixed
     * @throws NotExistException
     */
    public function show($id)
    {
        $product = SkuModel::with('product.category')->find($id);
        if(!$product) throw new NotExistException('库存不存在');
        return $product;
    }

    /**
     * 创建库存
     *
     * @param $data
     * @return static
     * @throws AlreadyExistException
     */
    public function create($data)
    {
        $sku = SkuModel::where('product_id', $data['product_id'])->where('canteen_id', $data['canteen_id'])->first();
        if($sku){
            throw new AlreadyExistException('物料已在库存中');
        }
        $quantity = $data['quantity'];
        unset($data['quantity']);
        $sku = SkuModel::create($data);
        $data['sku_id'] = $sku->id;
        unset($data['note']);
        $data['quantity'] = $quantity;
        $recordService = new Record();
        $recordService->create($data);
        return $sku;

    }

}